<?php
/**
 * Created by PhpStorm.
 * User: ZZF
 * Date: 2017/12/6
 * Time: 9:21
 */
namespace app\wechat\controller;
class GoodsController extends AuthController{

    public function detail(){
        $goods_id = input('id');
        $goods = db('Goods')->where(['id'=>$goods_id])->find();
        $images = db('GoodsImages')->where(['goods_id'=>$goods_id])->select();
        $comments = db('OrderComment')->where(['goods_id'=>$goods_id])->select();
        $goods['comment_count'] = count($comments);
        //商品规格 价钱 库存表 找出 所有 规格项id
        $keys = db('goods_attr_price')->where(['goods_id'=>$goods_id])->value("GROUP_CONCAT(`key` SEPARATOR '_') ");
        $attrs = array();
        if ($keys) {
            $keys = str_replace('_', ',', $keys);
            $filter_spec2 = db('goods_attribute')->alias('a')
                ->join('__GOODS_ATTR_VALUE__ b','b.attr_id=a.id','inner')
                ->where(array('b.id'=>array('in',$keys)))
                ->order('a.id')
                ->select();
            foreach ($filter_spec2 as $key => $val) {
                $attrs[$val['name']][] = array(
                    'item_id' => $val['id'],
                    'value' => $val['value'],
                );
            }
        }
        $this->assign([
            'goods'=>$goods,
            'attrs'=>$attrs,
            'attrs_json'=>json_encode($attrs),
            'images'=>$images,
            'comments'=>$comments,
        ]);
        return $this->fetch('detail');
    }

    /**
     * 获取商品规格的价格和库存
     */
    public function getGoodsAttrPriceStore()
    {
        $goods_id = input('param.goods_id');
        $attr_array = input('param.attr_key');
        $res = getGoodsAttrInfo($goods_id, $attr_array);
        if($res['status'] > 0){
            $attrInfo = [
                'price'=>$res['result']['price'],
                'vip_price'=>$res['result']['vip_price'],
                'store'=>$res['result']['store_count'],
                'name'=>$res['result']['key_name'],
            ];
            $this->ajaxReturn(['code'=>1,'result'=>$attrInfo]);
        }else{
            $this->ajaxReturn(['code'=>-1,'msg'=>'请求失败']);
        }
    }

    /**
     * 获取当前排队订单数量
     */
    public function getQueueNumber(){
        $cate_id = input('param.cate_id');

        $count = db('OrderGoods')->alias('g')
            ->join('__ORDER__ o','o.order_id = g.order_id','LEFT')
            ->where(['o.pay_status'=>1, 'o.order_status'=>0, 'g.cate_id'=>['like',"%$cate_id%"]])
            ->count();

        $this->ajaxReturn($count);
    }

}